package cn.iocoder.yudao.module.system.service.passengerinfo;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.system.controller.admin.passengerinfo.vo.PassengerInfoCreateReqVO;
import cn.iocoder.yudao.module.system.controller.admin.passengerinfo.vo.PassengerInfoPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.passengerinfo.vo.PassengerInfoUpdateReqVO;
import cn.iocoder.yudao.module.system.controller.app.passengerinfo.vo.PassengerComprehensiveVO;
import cn.iocoder.yudao.module.system.dal.dataobject.passengerinfo.PassengerInfoDO;
import cn.iocoder.yudao.module.system.dal.mysql.passengerinfo.PassengerInfoMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*;

/**
 * 乘客信息 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class PassengerInfoServiceImpl implements PassengerInfoService {

    @Resource
    private PassengerInfoMapper passengerInfoMapper;

    @Override
    public Long createPassengerInfo(PassengerInfoCreateReqVO createReqVO) {
        // 插入
        PassengerInfoDO passengerInfo = BeanUtils.toBean(createReqVO, PassengerInfoDO.class);
        passengerInfoMapper.insert(passengerInfo);
        // 返回乘客信息表的主键ID（Integer类型转Long）
        return passengerInfo.getPassengerInfoId().longValue();
    }

    @Override
    public void updatePassengerInfo(PassengerInfoUpdateReqVO updateReqVO) {
        // 校验存在
        validatePassengerInfoExists(updateReqVO.getId());
        // 更新
        PassengerInfoDO updateObj = BeanUtils.toBean(updateReqVO, PassengerInfoDO.class);
        passengerInfoMapper.updateById(updateObj);
    }

    @Override
    public void deletePassengerInfo(Long id) {
        // 校验存在
        validatePassengerInfoExists(id);
        // 删除
        passengerInfoMapper.deleteById(id);
    }

    private void validatePassengerInfoExists(Long id) {
        if (passengerInfoMapper.selectByIdWithJoin(id.intValue()) == null) {
            throw exception(PASSENGER_INFO_NOT_EXISTS);
        }
    }

    @Override
    public PassengerInfoDO getPassengerInfo(Long id) {
        return passengerInfoMapper.selectByIdWithJoin(id.intValue());
    }

    @Override
    public PageResult<PassengerInfoDO> getPassengerInfoPage(PassengerInfoPageReqVO pageReqVO) {
        // 计算offset，但保持原始pageReqVO不变
        PassengerInfoPageReqVO queryReqVO = BeanUtils.toBean(pageReqVO, PassengerInfoPageReqVO.class);
        int offset = (pageReqVO.getPageNo() - 1) * pageReqVO.getPageSize();
        queryReqVO.setPageNo(offset); // 将offset设置到查询对象中
        
        // 执行联表查询
        List<PassengerInfoDO> list = passengerInfoMapper.selectPageWithJoin(queryReqVO);
        Long total = passengerInfoMapper.selectCountWithJoin(queryReqVO);
        
        return new PageResult<>(list, total);
    }

    @Override
    public PassengerInfoDO getPassengerInfoByUserId(Long userId) {
        return passengerInfoMapper.selectByUserId(userId);
    }

    @Override
    public PassengerComprehensiveVO getMyPassengerComprehensiveInfo(Long userId) {
        // 调试信息
        System.out.println("Service层 - getMyPassengerComprehensiveInfo - userId: " + userId);
        
        // 根据userId获取乘客信息（包含用户信息的联表查询）
        PassengerInfoDO passengerInfo = passengerInfoMapper.selectByUserId(userId);
        
        System.out.println("Service层 - 查询到的乘客信息: " + (passengerInfo != null ? "存在" : "不存在"));
        
        if (passengerInfo == null) {
            // 如果没有乘客信息，返回空的综合信息
            System.out.println("Service层 - 返回空的综合信息");
            return new PassengerComprehensiveVO();
        }
        
        PassengerComprehensiveVO result = new PassengerComprehensiveVO();
        
        // 设置乘客基本信息
        PassengerComprehensiveVO.PassengerInfo passengerInfoVO = new PassengerComprehensiveVO.PassengerInfo();
        passengerInfoVO.setPassengerInfoId(passengerInfo.getPassengerInfoId());
        passengerInfoVO.setUserId(passengerInfo.getUserId());
        passengerInfoVO.setName(passengerInfo.getNickname() != null ? passengerInfo.getNickname() : passengerInfo.getUsername());
        passengerInfoVO.setPhone(passengerInfo.getMobile());
        passengerInfoVO.setLevel(passengerInfo.getLevel());
        passengerInfoVO.setGrowthValue(passengerInfo.getGrowthValue());
        passengerInfoVO.setKilometersAll(passengerInfo.getKilometersAll());
        passengerInfoVO.setKilometersMonth(passengerInfo.getKilometersMonth());
        passengerInfoVO.setTotalMoney(passengerInfo.getTotalMoney());
        passengerInfoVO.setPayMoneyAll(passengerInfo.getPayMoneyAll());
        passengerInfoVO.setPayMoneyMonty(passengerInfo.getPayMoneyMonty());
        passengerInfoVO.setYesInvoice(passengerInfo.getYesInvoice());
        passengerInfoVO.setNoInvoice(passengerInfo.getNoInvoice());
        passengerInfoVO.setRefundMoney(passengerInfo.getRefundMoney());
        result.setPassengerInfo(passengerInfoVO);
        
        // 设置用户基本信息
        PassengerComprehensiveVO.UserInfo userInfoVO = new PassengerComprehensiveVO.UserInfo();
        userInfoVO.setId(passengerInfo.getId());
        userInfoVO.setUsername(passengerInfo.getUsername());
        userInfoVO.setNickname(passengerInfo.getNickname());
        userInfoVO.setMobile(passengerInfo.getMobile());
        userInfoVO.setEmail(passengerInfo.getEmail());
        userInfoVO.setSex(passengerInfo.getSex());
        userInfoVO.setAvatar(passengerInfo.getAvatar());
        userInfoVO.setStatus(passengerInfo.getStatus());
        userInfoVO.setRealNameStatus(passengerInfo.getRealNameStatus());
        userInfoVO.setRealNameTime(passengerInfo.getRealNameTime());
        userInfoVO.setIdCard(passengerInfo.getIdCard());
        userInfoVO.setBalance(passengerInfo.getBalance());
        userInfoVO.setLoginDate(passengerInfo.getLoginDate());
        userInfoVO.setCreateTime(passengerInfo.getCreateTime());
        result.setUserInfo(userInfoVO);
        
        // TODO: 设置订单统计信息（需要从订单表查询）
        PassengerComprehensiveVO.OrderStats orderStats = new PassengerComprehensiveVO.OrderStats();
        orderStats.setTotalCount(0);
        orderStats.setCompletedCount(0);
        orderStats.setCancelledCount(0);
        orderStats.setMonthCount(0);
        orderStats.setTotalAmount(passengerInfo.getPayMoneyAll());
        orderStats.setMonthAmount(passengerInfo.getPayMoneyMonty());
        orderStats.setAvgRating(java.math.BigDecimal.valueOf(5.0));
        orderStats.setTotalDistance(passengerInfo.getKilometersAll());
        orderStats.setMonthDistance(passengerInfo.getKilometersMonth());
        result.setOrderStats(orderStats);
        
        // 设置会员信息
        PassengerComprehensiveVO.MemberInfo memberInfo = new PassengerComprehensiveVO.MemberInfo();
        memberInfo.setLevel(getLevelFromString(passengerInfo.getLevel()));
        memberInfo.setLevelName(passengerInfo.getLevel() != null ? passengerInfo.getLevel() : "普通会员");
        memberInfo.setPoints(0); // TODO: 从积分表查询
        memberInfo.setGrowthValue(passengerInfo.getGrowthValue());
        memberInfo.setNextLevelGrowth(0);
        memberInfo.setCouponCount(0);
        result.setMemberInfo(memberInfo);
        
        // TODO: 设置地址信息（需要从地址表查询）
        PassengerComprehensiveVO.AddressInfo addressInfo = new PassengerComprehensiveVO.AddressInfo();
        addressInfo.setHomeAddress("");
        addressInfo.setWorkAddress("");
        addressInfo.setCommonAddresses(new java.util.ArrayList<>());
        result.setAddressInfo(addressInfo);
        
        return result;
    }
    
    /**
     * 将字符串等级转换为数字等级
     */
    private Integer getLevelFromString(String levelStr) {
        if (levelStr == null) return 1;
        
        switch (levelStr) {
            case "银卡会员": return 2;
            case "金卡会员": return 3;
            case "VIP会员": return 4;
            default: return 1; // 普通会员
        }
    }

}